package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Reference;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

// 将动态的redis中的数据同步的mongo中
@Component
public class RecommentMovementJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 0/30 * * * ?")
    public void syncRecommentMovement() {
        System.out.println("推荐动态同步开始");

        // 1.获取redis中所有符合动态的key
        Set<String> keys = stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                // 2.获取userId
                Long userId = Long.parseLong(key.replaceAll("QUANZI_PUBLISH_RECOMMEND_", ""));
                // 3.获取当前用户所有的pid
                String pidStr = stringRedisTemplate.opsForValue().get(key);
                if (StrUtil.isNotEmpty(pidStr)) {
                    // 清除原来的推荐数据
                    mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId)), RecommendMovement.class);
                    stringRedisTemplate.delete(key);

                    String[] pidArr = pidStr.split(",");

                    for (String pid : pidArr) {
                        // 4.查询动态详情
                        Movement movement = mongoTemplate.findOne(Query.query(Criteria.where("pid").is(Long.parseLong(pid))), Movement.class);

                        // 5.保存推荐动态
                        RecommendMovement recommendMovement = new RecommendMovement();
                        recommendMovement.setCreated(System.currentTimeMillis());
                        recommendMovement.setUserId(userId);
                        recommendMovement.setPid(Long.parseLong(pid));
                        recommendMovement.setPublishId(movement.getId());
                        recommendMovement.setScore(RandomUtil.randomDouble(70, 100));
                        mongoTemplate.save(recommendMovement);
                    }
                }

            }
        }

        System.out.println("推荐动态同步结束");
    }
}
